﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Phone.Pdf;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

namespace ControlExplorer.Controls.Pdf
{
    public partial class DemoPdf
        : UserControl
    {
        private CancellationTokenSource _cancellationToken;

        public DemoPdf()
        {
            InitializeComponent();
        }


        public async void HandleButtonClick(object sender, RoutedEventArgs e)
        {
            loadingGrid.Visibility = System.Windows.Visibility.Visible;

            // get sender button
            var btn = sender as Button;
            await UploadPDFToWL((string)btn.Content);
        }

        private void CancelClick(object sender, RoutedEventArgs e)
        {
            if (_cancellationToken != null)
                _cancellationToken.Cancel();
        }

        #region ** uploading files to windows like - OneDrive

        private C1PdfDocument documentSaved;
        private string fileNameSaved;
        private OneDriveHelper wlHelper = new OneDriveHelper();

        public async Task UploadPDFToWL(string fileName)
        {
            fileNameSaved = fileName;
            try
            {
                await wlHelper.GetAccessToken(authorizationBrowser);
            }
            catch (OperationCanceledException exc)
            {
                this.loadingGrid.Visibility = Visibility.Collapsed;
                Dispatcher.InvokeAsync(() =>
                {
                    MessageBox.Show("You could not get an access token, please check your internet connection.");
                });
                return;
            }
            this.loadingGrid.Visibility = Visibility.Visible;
            this.loadingText.Text = "Getting folders from OneDrive...";
            try
            {
                var folders = await wlHelper.GetFolders();
                foldersList.ItemsSource = folders;
                selectFolder.Visibility = Visibility.Visible;
            }
            catch
            {

                MessageBox.Show("You should have at least a folder to upload the document to.");
            }
        }

        private async void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selFolder = foldersList.SelectedItem as WLFolder;
            if (selFolder != null)
            {
                selectFolder.Visibility = Visibility.Collapsed;

                loadingGrid.Visibility = Visibility.Visible;
                loadingProgress.IsIndeterminate = true;
                loadingText.Text = "Creating document...";
                Dispatcher.BeginInvoke(async () =>
                    {

                        try
                        {
                            // create document
                            var pdf = new C1PdfDocument(PaperKind.Letter);
                            documentSaved = pdf;
                            pdf.Clear();

                            // set document info
                            var di = pdf.DocumentInfo;
                            di.Author = "ComponentOne";
                            di.Subject = "C1.Silverlight.Pdf demo.";
                            di.Title = fileNameSaved;
                            // create document
                            switch (di.Title)
                            {
                                case "Images":
                                    PdfCodeSamples.CreateDocumentImages(pdf);
                                    break;
                                case "Paper Sizes":
                                    PdfCodeSamples.CreateDocumentPaperSizes(pdf);
                                    break;
                                case "Table of Contents":
                                    PdfCodeSamples.CreateDocumentTOC(pdf);
                                    break;
                                case "Text":
                                    PdfCodeSamples.CreateDocumentText(pdf);
                                    break;
                                case "Graphics":
                                    PdfCodeSamples.CreateDocumentGraphics(pdf);
                                    break;
                            }

                            // render footers
                            // this reopens each page and adds content to them (now we know the page count).
                            var font = new Font("Arial", 8, PdfFontStyle.Bold);
                            var fmt = new StringFormat();
                            fmt.Alignment = HorizontalAlignment.Right;
                            fmt.LineAlignment = VerticalAlignment.Bottom;
                            for (int page = 0; page < pdf.Pages.Count; page++)
                            {
                                pdf.CurrentPage = page;
                                var text = string.Format("C1.Silverlight.Pdf: {0}, page {1} of {2}",
                                    di.Title,
                                    page + 1,
                                    pdf.Pages.Count);
                                pdf.DrawString(
                                    text,
                                    font,
                                    Colors.DarkGray,
                                    PdfUtils.Inflate(pdf.PageRectangle, -72, -36),
                                    fmt);
                            }

                            // save document
                            loadingText.Text = "Uploading file to OneDrive...";
                            var stream = new MemoryStream();
                            documentSaved.Save(stream);
                            stream.Flush();
                            var contentType = "application/pdf";
                            var progress = new C1.Net.MultipartPostProgress(data =>
                            {
                                loadingProgress.IsIndeterminate = false;
                                loadingProgress.Value = data.Percentage;
                            });
                            _cancellationToken = new CancellationTokenSource();
                            var file = await wlHelper.UploadFileToWL(fileNameSaved + ".pdf", contentType, selFolder, stream, progress, _cancellationToken.Token);
                            loadingProgress.IsIndeterminate = true;
                            loadingGrid.Visibility = Visibility.Collapsed;
                            MessageBox.Show(string.Format("File '{0}' was uploaded to folder '{1}' of OneDrive.", fileNameSaved, selFolder.Name));
                        }
                        catch
                        {
                            this.loadingGrid.Visibility = Visibility.Collapsed;
                            MessageBox.Show("There was an error trying to upload the file to sky drive. Please try again.");
                        }
                    });
            }
        }

        #endregion
    }
}
